﻿#include "AccountBookDBManage.h"
#include <QDebug>

AccountBookDBManage* AccountBookDBManage::m_pInstance = nullptr;
AccountBookDBManage::AccountBookDBManage(){
//    connectDB();
}

AccountBookDBManage::~AccountBookDBManage()
{
    if (m_pInstance != NULL)
    {
        delete m_pInstance;
        m_pInstance = NULL;
    }
}
AccountBookDBManage *AccountBookDBManage::getInstance()
{
    if(m_pInstance == nullptr)
        m_pInstance = new AccountBookDBManage;
    return m_pInstance;
}

bool AccountBookDBManage::connectDB()
{
    m_database = QSqlDatabase::addDatabase("QSQLITE");
    m_database.setDatabaseName("F:/Programs/QT/2-HAPPINESS/AccountBook/AccountBookProj/DB/AccountBookDB.db");
//    m_database.setDatabaseName("DB/HFEMentalLoadAssessment.db");

//    qDebug() << m_database.databaseName();

    m_sql_query = QSqlQuery(m_database);
    if (!m_database.open())
    {
        qDebug() << "Error: Failed to connect database." << m_database.lastError();
        return false;
    }
    else
    {
        qDebug() << "Succeed to connect database." ;
        return true;
    }
}

// 设置数据库
void AccountBookDBManage::setDatabase(QString dbPath)
{
    m_database.close();
    m_sql_query.clear();

    m_database.setDatabaseName(dbPath);
    m_sql_query = QSqlQuery(m_database);
    if (!m_database.open())
    {
        qDebug() << "Error: Failed to connect database." << m_database.lastError();
        return;
    }
    else
    {
        qDebug() << "Succeed to connect database." ;
        return;
    }
}

// 获取当前数据库名称
QString AccountBookDBManage::getCurrentDBName()
{
    return m_database.databaseName();
}

bool AccountBookDBManage::exceSQL(QString sql)
{
    if(m_database.isOpen())
        m_database.open();
    m_sql_query = QSqlQuery(m_database);
    //打开外键 实现级联删除
    m_sql_query.exec("PRAGMA foreign_keys = ON");
    if(!m_sql_query.exec(sql))
    {
        qDebug() << __FUNCTION__ << __LINE__ << sql << m_sql_query.lastError();
        return false;
    }
    else
    {
        return true;
    }
}

bool AccountBookDBManage::addAccountItem(AccountItem item)
{
    QString sql = QString("INSERT INTO BillingDetailTable VALUES('%1', '%2', '%3', '%4', '%5', '%6');").arg(item.time.toString("yyyy-MM-dd")).arg(item.type).arg(item.amount).arg(item.inOrOut).arg(item.note).arg(item.currentTime.toString("yyyy-MM-dd hh:mm:ss"));
    return exceSQL(sql);
}

// 获取所有类型  支出-0 收入-1
QStringList AccountBookDBManage::searchStyleByInOrOut(int flag)
{
    QStringList lstStyle;
    QString sql;

    sql = QString("select styleType from StyleTable where inOrOut = '%1';").arg(flag);
    if(exceSQL(sql))
    {
        while(m_sql_query.next())
        {
            lstStyle << m_sql_query.value(0).toString();
        }
    }

    return lstStyle;
}

